<?php

namespace plugin\ycMassage\app\api\controller;

use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUserAddress;
use plugin\ycMassage\app\validate\MassageAddress;
use support\Request;
use think\facade\Db;

class AddressController extends BaseController
{
    protected $noNeedLogin = ["index"];
    public function getAddress(Request $request)
    {
        $model = MassageUserAddress::where(['uid' => $request->uid])->order('is_default desc')->select()->each(function ($item) {
            $item->mobile = substr_replace($item->mobile, '****', 3, 4);
        });
        return $this->successRes($model);
    }
    public function getAddressDetails(Request $request)
    {
        $id = $request->get('id');
        if ($id) {
            $model = MassageUserAddress::where(['id' => $id, 'uid' => $request->uid])->find();
            if (!$model) {
                return $this->fail('地址不存在');
            }
        } else {
            $model = MassageUserAddress::where(['uid' => $request->uid, 'is_default' => 1])->find();
            if (!$model) {
                return $this->fail('未设置默认地址');
            }
            if(!$model->latitude||!$model->longitude){
                return $this->fail('请重新选取位置');
            }
            $model->mobile = substr_replace($model->mobile, '****', 3, 4);
        }
        return $this->successRes($model);
    }
    public function saveAddress(Request $request)
    {
        $D = $request->post();
        $validate = new MassageAddress();
        if (!$validate->check($D)) {
            return $this->fail($validate->getError());
        }
        $D['uid'] = $request->uid;
        $D['saas_appid'] = $request->saas_appid;
        $model = new MassageUserAddress;
        if (!empty($D['id'])) {
            $model = MassageUserAddress::where(['id' => $D['id'], 'uid' => $request->uid])->find();
        }
        Db::startTrans();
        try {
            if ($D['is_default']) {
                MassageUserAddress::where(['uid' => $request->uid])->update(['is_default' => 0]);
            }
            $model->save($D);
            Db::commit();
            return $this->success('保存成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail('保存失败');
        }
    }
    public function deleteAddress(Request $request)
    {
        $ids = $request->post('ids');
        if (!$ids) {
            return $this->fail('参数错误');
        }
        $uid=$request->uid;
        $where=[
            ['id','in',$ids],
            ['uid','=',$uid]
        ];
        $model=MassageUserAddress::where($where)->select();
        if(!$model->isEmpty()){
            Db::startTrans();
            try {
                $model->delete();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail('删除失败');
            }
        }
        return $this->success('删除成功');
    }
}
